package cn.kuick.match3.test5;

import java.util.ArrayList;
import java.util.List;
/**
 * 
 * @author 春凡
 * 
 * 最长的绝对文件路径（Longest Absolute File Path）
 */
public class LongestAbsoluteFilePath_fan {

	public static void main(String[] args) {
		findLongestFilePath("aaa\n\tccccccc.txt\n\tbbb\n\t\tdddd.txt");
		findLongestFilePath("dir\n\tsubdir1\n\t\taaa.txt\n\t\tsubsubdir1\n\t\t\tbbb.txt\n\tsubdir2\n\t\tccc.txt\n\t\tdddddddddddddddddddddddd.txt");
	}
	
	private static String findLongestFilePath(String source){
		
		List<String> files = new ArrayList<>();
		
		String longestFile="";
		
		// 在第个\n前加一个/，用作分割符
		source = source.replace("\n", "/\n");
		
		// 根据/分割
		String[] strings = source.split("/");
		
		//取出根目录
		String path = strings[0];
		
		//从下标为1开始遍历
		for (int i = 1; i < strings.length; i++) {
			
			String item = strings[i];
			
			//切割出层级分割符
			String sperator = item.substring(0, item.lastIndexOf("\t")+1);
			
			if(path.contains(sperator)){
				
				//如果path中包含sperator，说明item的path的某一子目录平级,删除path中和item平级以下的目录
				path = path.substring(0, path.indexOf(sperator)); 
				path += item;
				
				//判断path是否是文件
				if(path.contains(".")){
					String temp = path.replace("\t", "").replaceAll("\n", "/");
					files.add(temp);
					
					if(temp.length()>longestFile.length()){
						longestFile = temp;
					}
				}
				
			}else{
				
				//如果path中不包含sperator，说明item是path的子目录，直接拼接
				path += item;
				
				//判断path是否是文件
				if(path.contains(".")){
					String temp = path.replace("\t", "").replaceAll("\n", "/");
					files.add(temp);
					
					if(temp.length()>longestFile.length()){
						longestFile = temp;
					}
				}
			}
		}
		
		
		for (int i = 0; i < files.size(); i++) {
			System.out.println(files.get(i)); 
		}
		
		System.out.println("longest file path = "+longestFile); 
		
		return longestFile;
	}
}
